package com.itheima.web.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.itheima.domain.cargo.Contract;
import com.itheima.domain.cargo.ContractExample;
import com.itheima.service.cargo.ContractService;
import com.itheima.util.DownloadUtil;
import com.itheima.domain.vo.ContractProductVo;
import com.itheima.web.controller.BaseController;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping(value = "/cargo/contract")
public class ContractController extends BaseController {

    @Reference
    private ContractService contractService;

    @RequestMapping(value = "/list", name = "分页查询合同列表")
    public String list(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "5") int size) {
        ContractExample example = new ContractExample();
        ContractExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(companyId);
        example.setOrderByClause(" create_time desc ");

        //如果登陆人是普通员工，增加一个条件createBy
        if (loginUser.getDegree() == 4) {
            criteria.andCreateByEqualTo(loginUser.getId());
        } else if (loginUser.getDegree() == 3) {
            //登陆人是部门管理人员
            criteria.andCreateDeptEqualTo(loginUser.getDeptId());
        } else if (loginUser.getDegree() == 2) {
            criteria.andCreateDeptLike(loginUser.getDeptId() + "%");
        }
        PageInfo pageInfo = contractService.findAll(example, page, size);
        request.setAttribute("page", pageInfo);
        return "cargo/contract/contract-list";
    }

    @RequestMapping(value = "/toAdd", name = "跳转合同添加页面")
    public String toAdd() {
        return "cargo/contract/contract-add";
    }


    @RequestMapping(value = "/edit", name = "合同增改操作")
    public String edit(Contract contract) {

        contract.setCompanyId(companyId);
        contract.setCompanyName(companyName);

        if (StringUtil.isEmpty(contract.getId())) {
            //新建
            contract.setId(UUID.randomUUID().toString());
            contract.setCreateTime(new Date());

            //设置合同上的登陆人
            contract.setCreateBy(loginUser.getId());
            //设置合同上的创建部门
            contract.setCreateDept(loginUser.getDeptId());

            contractService.save(contract);
        } else {
            //编辑
            contract.setCreateTime(new Date());
            contractService.update(contract);
        }

        return "redirect:/cargo/contract/list.do";
    }


    @RequestMapping(value = "/toUpdate", name = "跳转修改合同页面")
    public String toUpdate(String id) {
        Contract contract = contractService.findById(id);
        request.setAttribute("contract", contract);
        return "cargo/contract/contract-update";
    }


    @RequestMapping(value = "/delete", name = "删除合同")
    public String delete(String id) {
        contractService.delete(id);
        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping(value = "/print", name = "跳转到出货表打印页面")
    public String print() {
        return "cargo/print/contract-print";
    }

    @RequestMapping(value = "/printExcel", name = "打印出货表")
    public void printExcel(String inputDate) throws IOException {
        //1、通过inputDate查询出所有要导出excel表的数据，List<ContractProductVo>
        List<ContractProductVo> vos = contractService.findByInputDate(inputDate, companyId);
        //2、创建工作薄
        Workbook workbook = new SXSSFWorkbook();
        //3、创建页
        Sheet sheet = workbook.createSheet();
        //4、创建一个大标题，第一行第二个单元格写名称
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(1);
        cell.setCellValue(inputDate.replace("-", "年") + "月份出货表");
        //5、创建一个小标题
        row = sheet.createRow(1);

        cell = row.createCell(1);
        cell.setCellValue("客户");

        cell = row.createCell(2);
        cell.setCellValue("合同号");

        cell = row.createCell(3);
        cell.setCellValue("货号");

        cell = row.createCell(4);
        cell.setCellValue("数量");

        cell = row.createCell(5);
        cell.setCellValue("工厂");

        cell = row.createCell(6);
        cell.setCellValue("工厂交期");

        cell = row.createCell(7);
        cell.setCellValue("船期");

        cell = row.createCell(8);
        cell.setCellValue("贸易条款");
        //6、循环vo的list，得到每一个vo
        int index = 2;
        for (ContractProductVo vo : vos) {

            row = sheet.createRow(index);
            //7、在循环里，将vo数据写入单元格，创建单元格
            cell = row.createCell(1);
            cell.setCellValue(vo.getCustomName());

            cell = row.createCell(2);
            cell.setCellValue(vo.getContractNo());

            cell = row.createCell(3);
            cell.setCellValue(vo.getProductNo());

            cell = row.createCell(4);
            cell.setCellValue(vo.getCnumber());

            cell = row.createCell(5);
            cell.setCellValue(vo.getFactoryName());

            cell = row.createCell(6);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(vo.getDeliveryPeriod()));

            cell = row.createCell(7);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(vo.getShipTime()));

            cell = row.createCell(8);
            cell.setCellValue(vo.getTradeTerms());

            index++;
        }
        //8、循环外，导出excel表，使用工具类download
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        new DownloadUtil().download(outputStream,response,"出货表.xlsx");
    }

    @RequestMapping(value = "/printExcelByTemplate", name = "根据模板打印出货表")
    public void printExcelByTemplate(String inputDate, MultipartFile file) throws IOException {
        List<ContractProductVo> vos = contractService.findByInputDate(inputDate, companyId);
        Workbook workbook = new XSSFWorkbook(file.getInputStream());

        Sheet sheet = workbook.getSheetAt(0);
        Row row = sheet.getRow(0);
        Cell cell = row.getCell(1);
        cell.setCellValue(inputDate.replace("-","年")+"月份出货表");

        row = sheet.getRow(2);
        CellStyle[] cellStyles = new CellStyle[9];
        for (int i = 1; i < 9; i++) {
            cell = row.getCell(i);
            cellStyles[i] = cell.getCellStyle();
        }

        int index = 2;
        for (ContractProductVo vo : vos) {
            //8、循环里，创建行，创建单元格，设置单元格样式
            row = sheet.createRow(index);
            //设置行高
            row.setHeightInPoints(24);

            cell = row.createCell(1);
            cell.setCellValue(vo.getCustomName());
            cell.setCellStyle(cellStyles[1]);

            cell = row.createCell(2);
            cell.setCellValue(vo.getContractNo());
            cell.setCellStyle(cellStyles[2]);

            cell = row.createCell(3);
            cell.setCellValue(vo.getProductNo());
            cell.setCellStyle(cellStyles[3]);

            cell = row.createCell(4);
            cell.setCellValue(vo.getCnumber());
            cell.setCellStyle(cellStyles[4]);

            cell = row.createCell(5);
            cell.setCellValue(vo.getFactoryName());
            cell.setCellStyle(cellStyles[5]);

            cell = row.createCell(6);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(vo.getDeliveryPeriod()));
            cell.setCellStyle(cellStyles[6]);

            cell = row.createCell(7);
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(vo.getShipTime()));
            cell.setCellStyle(cellStyles[7]);

            cell = row.createCell(8);
            cell.setCellValue(vo.getTradeTerms());
            cell.setCellStyle(cellStyles[8]);

            index++;
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        workbook.write(outputStream);
        new DownloadUtil().download(outputStream,response,"模板出货表.xlsx");
    }

    @RequestMapping(value = "/submit", name = "提交购销合同")
    public String submit(String id) {
        Contract contract = new Contract();
        contract.setId(id);
        contract.setState(1);
        contractService.update(contract);
        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping(value = "/cancel", name = "取消购销合同")
    public String cancel(String id) {
        Contract contract = new Contract();
        contract.setId(id);
        contract.setState(0);
        contractService.update(contract);
        return "redirect:/cargo/contract/list.do";
    }

    @RequestMapping(value = "/toView", name = "跳转合同查看页面")
    public String toView(String id) {
        Contract contract = contractService.findById(id);
        request.setAttribute("contract", contract);
        return "cargo/contract/contract-view";
    }
}
